package com.ship.dispatch.service.fob.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.ConShipping;
import com.ship.dispatch.bean.SpFobSublease;
import com.ship.dispatch.bean.fob.*;
import com.ship.dispatch.bean.orderPay.ConFiles;
import com.ship.dispatch.bean.orderPay.SpFundManage;
import com.ship.dispatch.bean.orderPay.SpPaymentOrder;
import com.ship.dispatch.bean.orderPay.SpPaymentOrderDetail;
import com.ship.dispatch.bo.orderPay.SpPaymentOrderBO;
import com.ship.dispatch.bo.orderPay.SpPaymentOrderDetailBO;
import com.ship.dispatch.bpm.service.ProcessInstanceService;
import com.ship.dispatch.bpm.service.TaskService;
import com.ship.dispatch.bpm.utils.JsonUtils;
import com.ship.dispatch.bpm.vo.ManageEntityVo;
import com.ship.dispatch.bpm.vo.dto.BpmTaskDto;
import com.ship.dispatch.mapper.fob.SpFobSubleaseRentCompleteMapper;
import com.ship.dispatch.mapper.fob.SpFobSubleaseRentMapper;
import com.ship.dispatch.mapper.orderPay.ConFilesMapper;
import com.ship.dispatch.service.ConShippingService;
import com.ship.dispatch.service.SpDispatchSchemeExecuteService;
import com.ship.dispatch.service.SpFobSubleaseService;
import com.ship.dispatch.service.fob.*;
import com.ship.dispatch.service.orderPay.SpPaymentOrderService;
import com.ship.dispatch.util.WordUtil;
import com.ship.system.api.BpmInstanceService;
import com.ship.system.api.RemoteUserService;
import com.ship.system.api.domain.SysUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SpFobSubleaseRentCompleteServiceImpl extends FobBaseServiceImpl<SpFobSubleaseRentCompleteMapper, SpFobSubleaseRentComplete> implements SpFobSubleaseRentCompleteService {

    @Autowired(required = false)
    SpFobSubleaseRentCompleteMapper mapperapper;

    @Autowired
    SpFobFileRecordService spFobFileRecordService;

    @Autowired
    SpDispatchSchemeExecuteService schemeDetailService;

    @Autowired
    SpFobTemplateService spFobTemplateService;

    @Override
    public void updateEntity(ManageEntityVo manageEntityVo, String json) {
        SpFobSubleaseRentComplete object = JsonUtils.jsonToObject(json,SpFobSubleaseRentComplete.class);
        SpFobSubleaseRentComplete his = mapperapper.selectOne(new LambdaQueryWrapper<SpFobSubleaseRentComplete>().eq(SpFobSubleaseRentComplete::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobSubleaseRentComplete::getStatus,-2));
        if(his==null){ // 新增
            object.setSchemeDetailId(manageEntityVo.getSchemeDetailId());
            object.setTaskId(manageEntityVo.getTaskId());
            object.setProceeInstanceId(manageEntityVo.getProcessInstanceId());
            mapperapper.insert(object);
        }else { // 修改
            object.setId(his.getId());
            BeanUtils.copyProperties(object,his);
            mapperapper.updateById(his);
            // 处理多余文件记录
            his = mapperapper.selectOne(new LambdaQueryWrapper<SpFobSubleaseRentComplete>().eq(SpFobSubleaseRentComplete::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobSubleaseRentComplete::getStatus,-2));
            List<String> ids = new ArrayList<>();
            if(his.getFiels()!=null && his.getFiels().length()>0){
                String[] fieldIds = his.getFiels().split(",");
                ids =  Arrays.stream(fieldIds).collect(Collectors.toList());
            }
            if(his.getInvoiceTemplate()!=null && his.getInvoiceTemplate().length()>0){
                String[] fieldIds = his.getInvoiceTemplate().split(",");
                ids.addAll(Arrays.stream(fieldIds).collect(Collectors.toList()));
            }
            spFobFileRecordService.deleteOtherFileRecor(his.getId(),ids);
        }

    }

    @Override
    public SpFobBaseBean getBaseBeanByInstanceId(String id) {
        return mapperapper.selectOne(new LambdaQueryWrapper<SpFobSubleaseRentComplete>().eq(SpFobSubleaseRentComplete::getProceeInstanceId,id).ne(SpFobSubleaseRentComplete::getStatus,-2));
    }
    @Override
    public void  saveEntity(SpFobBaseBean bean){
        SpFobSubleaseRentComplete spFob = new SpFobSubleaseRentComplete();
        BeanUtils.copyProperties(bean,spFob);
        this.save(spFob);
    }

    @Override
    public void updateEntityById(SpFobBaseBean bean) {
        SpFobSubleaseRentComplete spFob = new SpFobSubleaseRentComplete();
        BeanUtils.copyProperties(bean,spFob);
        this.updateById(spFob);
    }


    @Override
    public Object getFormData(String id,Long serviceId) {
        SpFobSubleaseRentComplete spFobZzgcjr = null;
        if(serviceId!=null){
            spFobZzgcjr = mapperapper.selectById(serviceId);
        }else{
            spFobZzgcjr = mapperapper.selectOne(new LambdaQueryWrapper<SpFobSubleaseRentComplete>().eq(SpFobSubleaseRentComplete::getProceeInstanceId,id).ne(SpFobSubleaseRentComplete::getStatus,-2));
        }
        if(spFobZzgcjr==null){
            return null;
        }
        Map<String,Object> map = JsonUtils.jsonToMap(JsonUtils.objectToJson(spFobZzgcjr), Object.class);
        if(StringUtils.isNotBlank(spFobZzgcjr.getFiels())){
            String[] ids = spFobZzgcjr.getFiels().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("fiels",spFobFileRecordList);
        }
        if(spFobZzgcjr.getInvoiceTemplate()!=null){
            String[] ids = spFobZzgcjr.getInvoiceTemplate().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("invoiceTemplate",spFobFileRecordList);
        }
        SpFobSublease execute = spFobSubleaseService.getExceuteByInstanceId(spFobZzgcjr.getProceeInstanceId());
        ConShipping conShipping = conShippingService.getById(execute.getConId());
        if(conShipping!=null && map.containsKey("rent") && map.get("rent")==null){
            map.put("rent",conShipping.getRent());
            //map.put("currency",conShipping.getCurrency());
        }
        if(conShipping!=null && map.containsKey("currency") && map.get("currency")==null){
            //map.put("rent",conShipping.getRent());
            map.put("currency",conShipping.getCurrency());
        }
        return map;
    }
    @Override
    public List<Long> findServieData(String processInstanceId){
        List<SpFobSubleaseRentComplete> spFobBaseBeans =  mapperapper.selectList(new LambdaQueryWrapper<SpFobSubleaseRentComplete>().eq(SpFobSubleaseRentComplete::getProceeInstanceId,processInstanceId).orderByDesc(SpFobSubleaseRentComplete::getCreateDate));
        List<Long> list = spFobBaseBeans.stream().map(SpFobBaseBean::getId).collect(Collectors.toList());
        return list;
    }

    @Resource
    @Lazy
    ProcessInstanceService processInstanceService;
    @Override
    public void startPostInstance(Long businessId,String key){
        SpFobSubleaseRentComplete spFobZfzzcdyfk = this.getById(businessId);
        if(spFobZfzzcdyfk.getProceeInstanceId()!=null && spFobZfzzcdyfk.getApprovalStatus()!=null && spFobZfzzcdyfk.getApprovalStatus()==1){
            throw new BusException(" ，不可重复发起", BaseResultCode.GENERAL_ERROR);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("serviceType",key);
        map.put("moduleName","商务执行");
        map.put("reason","");
        String result = processInstanceService.createProcessInstance2(BpmInstanceService.SP_PAY_ORDER_EXISTS_SUBLEASE_BPM_KEY,map,businessId+"");
        spFobZfzzcdyfk.setApprovalProcess(result);
        spFobZfzzcdyfk.setApprovalStatus(0);
        spFobZfzzcdyfk.setCreateBy(SecurityUtils.getUsername());
        this.updateById(spFobZfzzcdyfk);
    }

    @Override
    public boolean checkApproveStatus(Long businessId) {
        SpFobSubleaseRentComplete spFobZfzzcdyfk = this.getById(businessId);
        //未开启审批可直接完成
        if(spFobZfzzcdyfk.getProceeInstanceId()==null){
            return true;
        }
        if(spFobZfzzcdyfk.getApprovalStatus()!=null && spFobZfzzcdyfk.getApprovalStatus()==1){
            return true;
        }
        return false;
    }

    @Resource
    @Lazy
    TaskService taskService;

    @Resource
    @Lazy
    RemoteUserService remoteUserService;

    @Resource
    WordUtil wordUtil;
    @Override
    @Transactional
    public void updateApprovaResult(Long businessId,Integer status){
        SpFobSubleaseRentComplete spFobZfzzcdyfk = this.getById(businessId);
        if(status==1 && (!StringUtils.isEmpty(spFobZfzzcdyfk.getInvoiceTemplate()) || StringUtils.isNotEmpty(spFobZfzzcdyfk.getField1()))){ // 处理业务说明文件不为空，更新业务文件
            List<BpmTaskDto> tasks = taskService.findActivitiOrFinishTaskResult(spFobZfzzcdyfk.getApprovalProcess());
            Map<String, SysUser> map = new HashMap<>();
            // 封装用户信息
            if(tasks.size()>=1){
                SysUser user = remoteUserService.getUserByName(tasks.get(0).getAssigneeId());
                user.setCreateTime(tasks.get(0).getFinishTime());
                map.put("业务部门负责人：",user);
                String userName = "";
                if(tasks.size()>1){
                    userName = tasks.get(1).getAssigneeId();
                    if(userName==null) userName = SecurityUtils.getUsername();
                    SysUser user2 = remoteUserService.getUserByName(userName);
                    user2.setCreateTime(tasks.get(1).getFinishTime());
                    map.put("业务审核人：",user2);
                }else{
                    SysUser user2 = new SysUser();
                    BeanUtils.copyProperties(user,user2);
                    //user2.setCreateTime(tasks.get(0).getFinishTime());
                    map.put("业务审核人：",user2);
                }
                SysUser user3 = remoteUserService.getUserByName(spFobZfzzcdyfk.getCreateBy());
                user3.setCreateTime(spFobZfzzcdyfk.getCreateDate());
                map.put("业务经办人：",user3);
            }
            if(!map.isEmpty()){
                wordUtil.updateFileTemplate(businessId,spFobZfzzcdyfk.getField1(),map,spFobZfzzcdyfk.getInvoiceTemplate());

                //wordUtil.updateFile(Long.parseLong(spFobZfzzcdyfk.getInvoiceTemplate()),map);
            }
        }
        //记录状态
        spFobZfzzcdyfk.setApprovalStatus(status);
        this.updateById(spFobZfzzcdyfk);
    }

    @Autowired(required = false)
    ConFilesMapper conFilesMapper;
    @Autowired
    SpPaymentOrderService spPaymentOrderService;

    public void createPayOrder(Long id){

        SpFobSubleaseRentComplete his = this.getById(id);

        if(his.getApprovalProcess()!=null && his.getApprovalStatus()!=null && his.getApprovalStatus()==1){
            List<SpFobSubleaseRentComplete> spFobBaseBeans =  mapperapper.selectList(new LambdaQueryWrapper<SpFobSubleaseRentComplete>().eq(SpFobSubleaseRentComplete::getProceeInstanceId,his.getProceeInstanceId()).isNull(SpFobSubleaseRentComplete::getOrderId));
            for(SpFobSubleaseRentComplete item:spFobBaseBeans){
                if(item!=null && item.getOrderId()==null){
                    Long orderId = createPayOrder(his.getProceeInstanceId(),item,his.getApprovalProcess());
                    item.setOrderId(orderId);
                    this.updateById(item);
                }
            }
        }
    }
    /**
     * 创建支付订单
     * @param processInstanceId
     * @param his
     */

    @Autowired
    @Lazy
    SpFobJsfhccbItemsService spFobJsfhccbItemsService;

    @Autowired
    SpFobSubleaseService spFobSubleaseService;

    @Autowired
    ConShippingService conShippingService;

    @Autowired
    SpFobSubleaseDeliveryUpdateService spFobSubleaseDeliveryUpdateService;

    @Autowired
    SpFobSubleaseRedeliveryUpdateService spFobSubleaseRedeliveryUpdateService;
    public Long createPayOrder(String processInstanceId,SpFobSubleaseRentComplete his,String approvalProceess){
        //完成节点 增加 订单支付记录
        //spPaymentOrderService.
        // 合同关联信息正常
        //SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(processInstanceId);
        SpFobSublease execute = spFobSubleaseService.getExceuteByInstanceId(processInstanceId);
        SpPaymentOrderBO spPaymentOrderBO = new SpPaymentOrderBO();
        spPaymentOrderBO.setContractId(his.getSchemeDetailId());
        //船舶租金首款
        spPaymentOrderBO.setOrderType(9);
        //contractType  船舶代理
        //List<SpFobJsfhccbItems> items = spFobJsfhccbItemsService.list(new LambdaQueryWrapper<SpFobJsfhccbItems>().eq(SpFobJsfhccbItems::getJsfhccbId,his.getId()).eq(SpFobJsfhccbItems::getTableId,"Part4").eq(SpFobJsfhccbItems::getA1,"合计"));
        if(StringUtils.isNotEmpty(his.getBalance())){
            spPaymentOrderBO.setPayAmount(new BigDecimal(his.getBalance()));
        }
        spPaymentOrderBO.setContractType(4);
        spPaymentOrderBO.setPayEndTime(his.getPlanEndDate());
        // spPaymentOrderBO.setVoyageNo(execute.getVoyageNo());
        spPaymentOrderBO.setPayAmountUnit(1);
        spPaymentOrderBO.setOrderStatus(3);
        ConShipping conShipping =  conShippingService.getById(execute.getConId());
        if(conShipping!=null){
            spPaymentOrderBO.setContractName(conShipping.getContractName());
        }
        List<ConFiles> conFiles = conFilesMapper.getConFilesByConIdAndFileType(conShipping.getId(),1);
        if(null !=conFiles && conFiles.size()>0){
            spPaymentOrderBO.setContractAddress(conFiles.get(0).getUrl());
        }
        spPaymentOrderBO.setApplicantPeople(SecurityUtils.getUsername());
        List<BpmTaskDto> tasks = taskService.findActivitiOrFinishTaskResult(approvalProceess);
        // 封装用户信息
        if(tasks.size()>=2){
            SysUser user = remoteUserService.getUserByName(tasks.get(0).getAssigneeId());
            if(user!=null){
                spPaymentOrderBO.setHandlePeople(user.getUserName());
            }
            SysUser user2 = remoteUserService.getUserByName(tasks.get(1).getAssigneeId());
            if(user2!=null){
                spPaymentOrderBO.setApprovedPeople(user2.getUserName());
            }
        }else if(tasks.size()>=1){
            SysUser user = remoteUserService.getUserByName(tasks.get(0).getAssigneeId());
            if(user!=null){
                spPaymentOrderBO.setHandlePeople(user.getUserName());
                spPaymentOrderBO.setApprovedPeople(user.getUserName());
            }
        }
        SpPaymentOrder order = spPaymentOrderService.synchronousPayOrder(spPaymentOrderBO);
        //对于订单明细
        SpPaymentOrderDetailBO spPaymentOrderDetailBO = new SpPaymentOrderDetailBO();
        spPaymentOrderDetailBO.setOrderId(order.getId());
        //spPaymentOrderDetailBO.setAdvancePayAmount(his.getPaymentAmount());
        //spPaymentOrderDetailBO.setBalanceAmount(his.getBalanceAmount());
        spPaymentOrderDetailBO.setPayableAmount(spPaymentOrderBO.getPayAmount());
        // spPaymentOrderDetailBO.setBalanceAmount(his.getBalanceAmount());
        String tradeBody = conShipping.getTradeBody()+"";
        if("1".equals(tradeBody)){
            spPaymentOrderDetailBO.setCnoocCorporation("CNOOC Gas and Power Trading& Marketing Limited");
        }else {
            spPaymentOrderDetailBO.setCnoocCorporation("CNOOC Gas and Power Singapore Trading& Marketing Pte. Ltd");
        }
        spPaymentOrderDetailBO.setShipName(execute.getShipName());
        SpFobSubleaseDeliveryUpdate spFobSubleaseDeliveryUpdate =  spFobSubleaseDeliveryUpdateService.findData(processInstanceId);
        if(spFobSubleaseDeliveryUpdate!=null){
            spPaymentOrderDetailBO.setExpectedLoadingPort(spFobSubleaseDeliveryUpdate.getDeliveryAddress());
            spPaymentOrderDetailBO.setExpectedLoadingDate(spFobSubleaseDeliveryUpdate.getDeliveryDate());
        }
        SpFobSubleaseRedeliveryUpdate spFobSubleaseRedeliveryUpdate= spFobSubleaseRedeliveryUpdateService.findData(processInstanceId);
        if(spFobSubleaseRedeliveryUpdate!=null){
            spPaymentOrderDetailBO.setExpectedUnloadingDate(spFobSubleaseRedeliveryUpdate.getRedeliveryDate());
            spPaymentOrderDetailBO.setExpectedUnloadingPort(spFobSubleaseRedeliveryUpdate.getRedeliveryAddress());
        }
        //spPaymentOrderDetailBO.setRealityLoadingDate(execute.getRealityLoadingDate());
        SpPaymentOrderDetail detail = spPaymentOrderService.synchronousPayOrderDetail(spPaymentOrderDetailBO);
        //同步资金管理
        SpFundManage fundManage = spPaymentOrderService.synchronousSpFundManage(order,detail);
        if(null != fundManage){
            //同步资金详情管理
            spPaymentOrderService.synchronousSpFundManageDetail(detail,fundManage.getId(),fundManage.getAccountBalance());
        }
        return order.getId();
    }

    @Autowired
    SpFobSubleaseRentService spFobSubleaseRentService;
    @Override
    public String findData(String processInstanceId) {
        BigDecimal num = mapperapper.findBalances(processInstanceId);
        BigDecimal num2 =  spFobSubleaseRentService.findBalances(processInstanceId);
        if(num==null){
           num = new BigDecimal(0);
        }
        num = num.add(num2);
        return num+"";
    }
}
